<template>
  <div class="notice">
    <div class="container">
      <div class="search-card">
        <div class="search-argument">
          <!-- 公告名称 -->
          <div class="search-item">
            <span class="labelName">{{ $t("publicInfo.NoticeTitle") }}</span>
            <el-input
              clearable
              v-model="params.noticeTitle"
              class="search-input"
              maxlength="20"
              :placeholder="$t('placeholder.NoticeTitle')"
            ></el-input>
          </div>
          <!-- 搜索按钮 -->
          <div class="search-button">
            <div class="btn search" @click="getNoticeList">
              <el-icon class="icon"> <Search /> </el-icon
              >{{ $t("common.search") }}
            </div>
            <div class="btn reset" @click="resetSearch">
              <el-icon class="icon"> <Refresh /> </el-icon
              >{{ $t("common.reset") }}
            </div>
          </div>
        </div>
        <div class="batch-operation">
          <el-button
            class="btn search"
            @click="openFormDialog('add')"
            v-hasPermi="['publicInfo:notice:add']"
          >
            <el-icon class="icon"> <Plus /> </el-icon
            >{{ $t("publicInfo.AddNotice") }}
          </el-button>
          <el-button
            v-if="deleteIds.length > 0"
            class="btn remove"
            @click="deletePrompt()"
            v-hasPermi="['publicInfo:notice:remove']"
          >
            <el-icon class="icon"> <Delete /> </el-icon
            >{{ $t("common.BatchDeletion") }}
          </el-button>
          <el-button
            v-else
            class="btn cantUse"
            v-hasPermi="['publicInfo:notice:remove']"
          >
            <el-icon class="icon"> <Delete /> </el-icon
            >{{ $t("common.BatchDeletion") }}
          </el-button>
        </div>
      </div>

      <!-- 表格数据 -->
      <el-table
        v-loading="loading"
        :data="noticeList"
        :border="true"
        max-height="60vh"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column
          type="index"
          :label="$t('publicInfo.SerialNo')"
          :index="indexMethod"
          width="85"
          align="center"
        />
        <!-- 操作 -->
        <el-table-column
          :label="$t('publicInfo.Operate')"
          align="center"
          min-width="120"
          class-name="small-padding fixed-width"
        >
          <template #default="{ row }">
            <el-button
              link
              type="primary"
              @click="openFormDialog('detail', row.noticeId)"
              v-hasPermi="['publicInfo:notice:detail']"
              >{{ $t("common.detail") }}</el-button
            >
            <el-button
              link
              type="primary"
              @click="openFormDialog('edit', row.noticeId)"
              v-hasPermi="['publicInfo:notice:edit']"
              >{{ $t("common.edit") }}</el-button
            >
            <el-button
              link
              type="danger"
              @click="deletePrompt(row.noticeId)"
              v-hasPermi="['publicInfo:notice:remove']"
              >{{ $t("common.delete") }}</el-button
            >
          </template>
        </el-table-column>
        <!-- 状态 -->
        <el-table-column
          :label="$t('publicInfo.Status')"
          align="center"
          min-width="100"
        >
          <template #default="{ row }">
            <span class="tag info" v-if="row.status === 2">{{
              $t("publicInfo.Delisted")
            }}</span>
            <span class="tag warning" v-if="row.status === 1">{{
              $t("publicInfo.Unpublished")
            }}</span>
            <span class="tag success" v-if="row.status === 0">{{
              $t("publicInfo.Published")
            }}</span>
          </template>
        </el-table-column>
        <el-table-column
          :label="$t('publicInfo.NoticeTitle')"
          prop="noticeTitle"
          :show-overflow-tooltip="true"
          min-width="85"
          align="center"
        />
        <el-table-column
          :label="$t('publicInfo.File')"
          :show-overflow-tooltip="true"
          min-width="85"
          align="center"
        >
          <template #default="{ row }">
            <span>{{
              `${row.tlowairServiceFileDto.fileName}.${row.tlowairServiceFileDto.fileExtension}`
            }}</span>
          </template>
        </el-table-column>
        <el-table-column
          :label="$t('publicInfo.UpdateTime')"
          align="center"
          min-width="150"
        >
          <template #default="{ row }">
            <span>{{ dataFormat(row.updateTime, "YYYY-MM-DD HH:mm") }}</span>
          </template>
        </el-table-column>
        <el-table-column
          :label="$t('publicInfo.ReleaseTime')"
          align="center"
          min-width="150"
        >
          <template #default="{ row }">
            <span>{{
              dataFormat(row.noticeReleaseTime, "YYYY-MM-DD HH:mm")
            }}</span>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="params.pageNum"
        v-model:limit="params.pageSize"
        @pagination="getNoticeList"
        class="pagination"
      />

      <!-- 新增弹出层 -->
      <el-dialog
        v-model="addNewVisible"
        :title="formTitle"
        class="add-dialog"
        :close-on-click-modal="false"
        @close="closeDialog(noticeFormRef)"
      >
        <el-form
          :label-width="Lang === 'en' ? '120px' : '100px'"
          ref="noticeFormRef"
          :model="noticeForm"
          :rules="rules"
        >
          <el-form-item
            :label="$t('publicInfo.NoticeTitle')"
            prop="noticeTitle"
          >
            <el-input
              :disabled="isDisabled"
              v-model="noticeForm.noticeTitle"
              maxlength="20"
              :placeholder="$t('placeholder.NoticeTitle')"
            />
          </el-form-item>
          <el-form-item :label="$t('publicInfo.NoticeFile')" prop="file">
            <Upload
              :fileList="fileList"
              :isCanDelete="isCanDelete"
              :isFull="true"
              :showButton="showButton"
              @success="uploadSuccess"
              @deleteFile="deleteFile"
            />
          </el-form-item>
          <el-form-item
            :label="$t('publicInfo.ReleaseTime')"
            prop="noticeReleaseTime"
          >
            <el-date-picker
              :disabled="isDisabled"
              v-model="noticeForm.noticeReleaseTime"
              type="datetime"
              format="YYYY-MM-DD HH:mm"
              :placeholder="$t('placeholder.ReleaseTime')"
              style="width: 100%"
            />
          </el-form-item>
          <el-form-item :label="$t('publicInfo.Status')" prop="status">
            <el-select
              :disabled="isDisabled"
              v-model="noticeForm.status"
              style="width: 100%"
              :placeholder="$t('placeholder.ReleaseStatus')"
            >
              <el-option
                v-for="item in statusList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('publicInfo.Remark')">
            <el-input
              :disabled="isDisabled"
              v-model="noticeForm.remark"
              :placeholder="$t('placeholder.remark')"
              maxlength="150"
              :rows="3"
              type="textarea"
            />
          </el-form-item>
          <div class="dialogFoot">
            <div class="btn delete" @click="closeDialog(noticeFormRef)">
              {{ isDisabled ? $t("common.close") : $t("common.cancel") }}
            </div>
            <div
              v-if="!isDisabled"
              class="btn search"
              @click="submit(noticeFormRef)"
            >
              {{ $t("common.confirm") }}
            </div>
          </div>
        </el-form>
      </el-dialog>

      <!-- 删除弹出层 -->
      <el-dialog v-model="deleteVisible" class="no-header-dialog">
        <img src="@/assets/images/warn.png" alt="" />
        <div class="dec">
          确定删除选中的 <span class="deletecolor">公告</span> 吗？
        </div>
        <div class="chooise">
          <div class="btn delete" @click="closeDelete">
            {{ $t("common.cancel") }}
          </div>
          <div class="btn success" @click="deleteApply">
            {{ $t("common.confirm") }}
          </div>
        </div>
      </el-dialog>
    </div>
  </div>
</template>
<script>
export default {
  name: "Notices",
};
</script>
<script setup>
import { computed, onMounted, reactive, ref, watch } from "vue";
import { ElMessage } from "element-plus";
import {
  getNoticeListApi,
  deleteNoticeApi,
  getNoticeDetailApi,
  saveNoticeApi,
  updateNoticeApi,
} from "@/api/publickInfo/notice";
import { deleteFiles } from "@/api/upload";
import Upload from "@/components/Upload/index";
import { dataFormat } from "@/utils/format";
import { getCurrentInstance } from "vue";

const { $t } = getCurrentInstance().proxy;
const loading = ref(false);
const noticeList = ref([]);
const addNewVisible = ref(false);
const deleteVisible = ref(false);
const statusList = reactive([
  {
    label: "启用",
    value: 6,
  },
  {
    label: "停用",
    value: 2,
  },
]);
const noticeFormRef = ref();
// 请求参数
const params = reactive({
  noticeTitle: null,
  pageNum: 1,
  pageSize: 10,
});
const total = ref(3);
const fileList = ref([]);
const showButton = ref(true);
const isCanDelete = ref(true);
const deleteIds = ref([]);
const deleteId = ref();

const isDisabled = computed(() => {
  return formTitle.value === $t("publicInfo.NoticeDetail");
});
const Lang = computed(() => {
  return localStorage.getItem("currentLang");
});
// -------------------------------------------------  获取列表数据  -----------------------------------------------------
/**
 * @获取列表
 */
const getNoticeList = async () => {
  try {
    loading.value = true;
    const res = await getNoticeListApi(params);
    noticeList.value = res.rows;
    total.value = res.total;
    loading.value = false;
  } catch (error) {
    loading.value = false;
  }
};

/**
 * @重置搜索参数
 */
const resetSearch = () => {
  params.noticeTitle = null;
  params.pageNum = 1;
  params.pageSize = 10;
  getNoticeList();
};

/**
 * @文件上传成功回调函数
 */
const uploadSuccess = (data) => {
  fileList.value.push(data);
  noticeFormRef.value.validateField();
};

/**
 * @删除上传文件回调函数
 */
const deleteFile = async (index, fileId) => {
  fileList.value.splice(index, 1);
  if (fileId) {
    const res = await deleteFiles(fileId);
    if (res.code === 200) ElMessage.success("文件已成功删除！");
  }
};

/**
 * @监听上传文件
 */
watch(fileList.value, (newV, oldV) => {
  if (fileList.value.length > 0) {
    showButton.value = false;
    noticeForm.value.file = fileList.value[0];
  } else {
    showButton.value = true;
    noticeForm.value.file = {};
  }
});

// -------------------------------------------------  表单事件  -----------------------------------------------------
/**
 * @表单对象
 * */
const noticeForm = ref(initForm());
/**
 * @表单校验规则
 * */
const rules = reactive({
  noticeTitle: [{ required: true, message: "请输入公告标题", trigger: "blur" }],
  file: [
    // {  message: "请上传公告文件", trigger: "change" },
    {
      required: true,
      validator: (rule, value, callback) => {
        if (!value.url) {
          callback(new Error("请上传公告文件"));
        }
        callback();
      },
    },
  ],
  noticeReleaseTime: [
    { required: true, message: "请选择发布时间", trigger: "change" },
  ],
  status: [{ required: true, message: "请输入公告标题", trigger: "change" }],
});
/**
 * @初始化表单
 * */
function initForm() {
  return {
    noticeTitle: null,
    file: {},
    noticeReleaseTime: null,
    status: null,
    statusName: null,
    remark: null,
  };
}

/**
 * @提交表单
 * */
const submit = async (formEl) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      let { noticeReleaseTime, updateTime } = noticeForm.value;
      let res = null;
      noticeReleaseTime = dataFormat(noticeReleaseTime, "YYYY-MM-DD HH:mm:ss");
      if (updateTime) delete noticeForm.value.updateTime;
      // delete noticeForm.value.tlowairServiceFileDto;
      if (noticeForm.value.noticeId) {
        res = await updateNoticeApi({
          ...noticeForm.value,
          noticeReleaseTime,
        });
      } else {
        res = await saveNoticeApi({
          ...noticeForm.value,
          noticeReleaseTime,
        });
      }
      if (res.code === 200) ElMessage.success(res.msg);
      else ElMessage.error(res.msg);
      await getNoticeList();
      addNewVisible.value = false;
      noticeForm.value = initForm();
      deleteFile(0);
    } else {
      console.log("error submit!", fields);
    }
  });
};

// -------------------------------------------------  删除事件  -----------------------------------------------------
const deletePrompt = (id) => {
  deleteVisible.value = true;
  if (id) deleteId.value = id;
};

const closeDelete = () => {
  deleteVisible.value = false;
  deleteId.value = null;
};

const deleteApply = async () => {
  let ids = deleteId.value || deleteIds.value;
  const res = await deleteNoticeApi(ids);
  if (res.code === 200) ElMessage.success(res.msg);
  else ElMessage.error(res.msg);
  await getNoticeList();
  deleteVisible.value = false;
  deleteIds.value = [];
  deleteId.value = null;
};
function handleSelectionChange(selection) {
  deleteIds.value = selection.map((item) => item.noticeId);
}

// -------------------------------------------------  弹出层事件  -----------------------------------------------------
const formTitle = ref("");
/**
 * @打开表单弹出层
 * @openType 打开弹出层的操作类型，根据不同类型修改弹出层标题
 * */
const openFormDialog = async (openType, id) => {
  addNewVisible.value = true;
  if (openType === "add") formTitle.value = $t("publicInfo.AddNotice");
  if (openType === "edit") {
    formTitle.value = $t("publicInfo.EditNotice");
    const { data } = await getNoticeDetailApi(id);
    if (data.tlowairServiceFileDto.url)
      fileList.value.push(data.tlowairServiceFileDto);
    noticeForm.value = data;
    if (data.status !== 2) noticeForm.value.status = 6;
  }
  if (openType === "detail") {
    formTitle.value = $t("publicInfo.NoticeDetail");
    isCanDelete.value = false;
    const { data } = await getNoticeDetailApi(id);
    if (data.tlowairServiceFileDto.url)
      fileList.value.push(data.tlowairServiceFileDto);
    noticeForm.value = data;
    if (data.status !== 2) noticeForm.value.status = 6;
    if (!data.remark) noticeForm.value.remark = "暂无数据";
  }
};

/**
 * @关闭详情表单弹出层
 * */
const closeDialog = (formEl) => {
  // if (!formEl) return;
  formEl.resetFields();
  addNewVisible.value = false;
  isCanDelete.value = true;
  noticeForm.value = initForm();
  deleteFile(0);
};

// -----------------------------------  序号  ----------------------------------
function indexMethod(index) {
  // 当前页码
  const currentPage = params.pageNum;
  // 每页显示的数据条数
  const pageSize = params.pageSize;
  // 当前行的实际索引
  const truelndex = (currentPage - 1) * pageSize + index + 1;
  // 如果当前行的索引大于等于当前页的最大索引，
  // 则使用当前行的实际索引，否则使用当前行的原始索引
  return truelndex;
}

onMounted(() => {
  getNoticeList();
});
</script>

<style lang="scss" scoped>
.notice {
  .add-dialog .el-dialog__body {
    padding: 20px;
  }

  .search-item .search-input .el-input,
  .search-time .el-date-editor {
    height: 40px !important;
  }
}
</style>

<style scoped lang="scss">
.notice {
  width: 100%;
  height: 100%;

  .container {
    position: relative;
    width: calc(100% - 40px);
    height: 92%;
    margin: 0 20px 20px;
    border-radius: 10px;
    background: white;

    .pagination {
      position: absolute;
      left: 50%;
      bottom: 30px;
      transform: translateX(-50%);
    }
  }

  .search-card {
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    align-items: flex-start;
    padding: 30px 0;
    width: 100%;
    height: 100px;
    border-radius: 10px;
    background-color: #fff;
  }

  .search-argument {
    width: 100%;
    display: flex;
    flex-wrap: wrap;
    justify-content: flex-start;
    align-content: flex-start;
    gap: 20px;

    .search-item {
      display: flex;
      justify-content: flex-start;
      align-items: center;
      width: 24%;
      height: 40px;

      .search-input {
        flex: 1;
        width: 270px;
        height: 40px;
      }
    }

    .labelName {
      display: inline-block;
      width: 80px;
      text-align: right;
      font-size: 14px;
      margin-right: 15px;
    }

    .search-button {
      position: absolute;
      right: 0px;
      top: -45px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      width: 160px;
      height: 40px;
    }
  }

  .batch-operation {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    position: absolute;
    right: 180px;
    top: -45px;
    height: 40px;
  }

  .tag {
    display: inline-block;
    width: 80px;
    height: 30px;
    line-height: 30px;
    text-align: center;
    border-radius: 15px;
    color: rgba(153, 153, 153, 1);
    // border: 1px solid rgba(153, 153, 153, 1);
  }
  .tag.warning {
    color: rgba(255, 149, 18, 1);
    // border: 1px solid rgba(255, 149, 18, 1);
  }
  .tag.success {
    color: rgba(43, 193, 123, 1);
    // border: 1px solid rgba(43, 193, 123, 1);
  }

  .btn {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 34px;
    padding: 10px;
    font-size: 14px;
    border-radius: 4px;
    user-select: none;
    cursor: pointer;
  }
  .btn.search {
    color: #fff;
    background: rgba(43, 193, 123, 1);
    &:hover {
      background: rgba(43, 193, 123, 0.85);
    }
  }

  .btn.reset {
    color: rgba(43, 193, 123, 1);
    background: rgba(43, 193, 123, 0.05);
    border: 1px solid rgba(43, 193, 123, 1);
    &:hover {
      background: rgba(43, 193, 123, 0.2);
    }
  }

  .btn.cantUse {
    color: rgba(255, 149, 18, 0.5);
    background: rgba(255, 149, 18, 0.05);
    border: 1px solid rgba(255, 149, 18, 0.5);
    cursor: not-allowed;
  }

  .btn.remove {
    color: rgba(255, 149, 18, 1);
    background: rgba(255, 149, 18, 0.05);
    border: 1px solid rgba(255, 149, 18, 1);
    &:hover {
      background: rgba(255, 149, 18, 0.2);
    }
  }

  .icon {
    margin-right: 6px;
  }
}
</style>
